#include<stdio.h>
#include<pthread.h>

//一个顾客一个厨师
//

int counter=0;  //0-柜台没饭，1-柜台有饭

pthread_mutex_t mutex;  //定义互斥锁
pthread_cond_t cond;  //定义条件变量

void* Customer(void* arg){
  while(1){
    pthread_mutex_lock(&mutex);   //首先加锁
    if(counter==0){  //判断有无饭
      //柜台没有饭，需要阻塞等待----解锁-休眠-被唤醒后加锁
      pthread_cond_wait(&cond,&mutex);
    }
    //否则，counter = 1 有饭
    printf("饭好吃，再来一碗！\n");
    counter=0;
    pthread_cond_signal(&cond);  //唤醒厨师做饭
    pthread_mutex_unlock(&mutex);  //解锁
  }
  return 0;
}

void* Cook(void* arg){
  while(1){
    pthread_mutex_lock(&mutex);  //首先加锁
    if(counter==1){
      //有饭，则阻塞
      pthread_cond_wait(&cond,&mutex);
    }
    //否则，counter = 0 没有饭，需要做饭
    printf("饭好了，快来吃饭！\n");
    counter=1;
    pthread_cond_signal(&cond);   //唤醒顾客
    pthread_mutex_unlock(&mutex);  //解锁
  }
  return 0;
}

int main()
{
  //创建两个线程----顾客，厨师
  pthread_t cus_tid,cook_tid;
  int ret;
  //初始化操作----初始化互斥锁与条件变量
  pthread_mutex_init(&mutex,NULL);
  pthread_cond_init(&cond,NULL);

  ret=pthread_create(&cus_tid,NULL,Customer,NULL);
  if(ret!=0){
    perror("pthread_create error!\n");
    return -1;
  }
  ret=pthread_create(&cook_tid,NULL,Cook,NULL);
  if(ret!=0){
    perror("pthread_create error!\n");
    return -1;
  }


  //线程等待
  pthread_join(cus_tid,NULL);
  pthread_join(cook_tid,NULL);


  //销毁
  pthread_mutex_destroy(&mutex);
  pthread_cond_destroy(&cond);

  return 0;
}
